package sng.modules.view.components.city.logic
{
	import as3isolib.display.IsoView;
	import as3isolib.display.scene.IsoScene;
	import as3isolib.geom.IsoMath;
	import as3isolib.geom.Pt;
	
	import eDpLib.events.ProxyEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.managers.CursorManager;
	
	import sng.modules.view.components.city.cursor.CityCursor;
	import sng.modules.view.components.city.cursor.CityCursorManager;
	import sng.modules.view.components.city.logic.unit.BaseBuilding;
	import sng.modules.view.components.city.logic.unit.Tile;
	import sng.modules.view.components.city.state.CityMoveState;
	import sng.utils.BuildingUtil;
	import sng.utils.IsoUtil;

	/**
	 * 控制建筑移动，添加，删除的Scene
	 * 
	 * @author easonyang
	 */
	public class GroundScene extends IsoScene
	{
		private var _gridCols:int;
		private var _gridRows:int;
		private var _gridCellsize:int;
		private var _city:City;
		private var _cityView:CityView;
		private const GRID_EXTEND_LENGTH:int=10; //网格负方向拓展格数。
		private var _buildingInfoGridArr:Array; //记录建筑在网格上的投影信息，用以判断当前鼠标所指的建筑。
		private var _mouseOverBuilding:BaseBuilding; //当前mouseOver所指的建筑。
		private var _mouseOverEnable:Boolean;
		private var _tileClickEnable:Boolean;
		private var _mouseCursorContainer:Sprite;
		private var _isDisenableTileClickOnce:Boolean
		
		/**
		 *
		 * @param gridCols
		 * @param gridRows
		 */
		public function GroundScene(gridCols:int, gridRows:int, gridCellsize:int, city:City, cityView:CityView)
		{
			super();
			this._gridCols=gridCols;
			this._gridRows=gridRows;
			this._city=city;
			this._cityView=cityView;
			this._gridCellsize=gridCellsize;
			_city.addEventListener(MouseEvent.CLICK, onGroundSceneClik, true);
			this.addEventListener(Event.ENTER_FRAME, onCityEnterFrame);
			_mouseOverEnable=true;
			_tileClickEnable=true;
//			this.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
		}
		
		/**
		 * 初始化指针
		 */ 
		public function initCityCursor(mouseCursorContainer:Sprite):void
		{
			_mouseCursorContainer=mouseCursorContainer;
			CityCursorManager.getInstance().initCursorContainer(_mouseCursorContainer);
		}

		/**
		 * 初始化_buildingInfoGridArr成3维数组
		 */
		public function initBuildingInfoGridArr():void
		{
			_buildingInfoGridArr=new Array();
			var i:int;
			var j:int;
			for (i=0; i < _gridCols + GRID_EXTEND_LENGTH*2; i++)
			{
				var arr:Array=new Array();
				for (j=0; j < _gridRows + GRID_EXTEND_LENGTH*2; j++)
				{
					arr.push(new Array());
				}
				_buildingInfoGridArr.push(arr);
			}
		}

		/**
		 * 添加建筑
		 */
		public function addTile(tile:Tile, col:Number, row:Number, cityView:CityView, zeroHeight:Boolean=false):void
		{
			tile.cityView=cityView;
			tile.spawnAt(col, row, 0);
			this.addChild(tile);
			IsoUtil.updateAllMapDataInfo(tile as BaseBuilding,true);
		}
		
		/**
		 * 删除建筑
		 */
		public function removeTile(tile:Tile):void
		{
			if (this.contains(tile))
			{
				IsoUtil.updateAllMapDataInfo(tile as BaseBuilding,false);
				this.removeChild(tile);
				//有用？ eason 20110715
//				tile.dispose();
			}
		}
		
		/**
		 * 删除所有建筑
		 */
		public function removeAllTile():void
		{
			while(this.numChildren>0)
			{
				var tile:Tile = this.getChildAt(this.numChildren-1) as Tile;
				IsoUtil.updateAllMapDataInfo(tile as BaseBuilding,false);
				this.removeChild(tile);
				//有用？ eason 20110715
//				if(tile==null)
//					tile.dispose();
			}
		}

		/**
		 * 更新buildingInfoGridArr
		 * 如果网格保存有value，则删除value
		 * 如果网格没有保存value，则添加value
		 */
		public function updateBuildingInfoGridArr(tile:Tile, isAdd:Boolean):void
		{
			var isoPt:Pt=IsoMath.isoToScreen(new Pt(tile.x, tile.y));
			var isoLBPt:Pt=IsoMath.screenToIso(new Pt(isoPt.x - (tile as BaseBuilding).vo.width / 2, isoPt.y)); //左下角
			var isoLTPt:Pt=IsoMath.screenToIso(new Pt(isoPt.x - (tile as BaseBuilding).vo.width / 2., isoPt.y - (tile as BaseBuilding).vo.height)); //左上角
			var isoRBPt:Pt=IsoMath.screenToIso(new Pt(isoPt.x + (tile as BaseBuilding).vo.width / 2, isoPt.y)); //右下角
			var isoRTPt:Pt=IsoMath.screenToIso(new Pt(isoPt.x + (tile as BaseBuilding).vo.width / 2, isoPt.y - (tile as BaseBuilding).vo.height)); //右上角
			var lbPt:Object=new Object();
			lbPt.col=Math.floor(isoLBPt.x / _gridCellsize) + GRID_EXTEND_LENGTH;
			lbPt.row=Math.floor(isoLBPt.y / _gridCellsize) + GRID_EXTEND_LENGTH;
			var ltPt:Object=new Object();
			ltPt.col=Math.floor(isoLTPt.x / _gridCellsize) + GRID_EXTEND_LENGTH;
			ltPt.row=Math.floor(isoLTPt.y / _gridCellsize) + GRID_EXTEND_LENGTH;
			var rbPt:Object=new Object();
			rbPt.col=Math.floor(isoRBPt.x / _gridCellsize) + GRID_EXTEND_LENGTH;
			rbPt.row=Math.floor(isoRBPt.y / _gridCellsize) + GRID_EXTEND_LENGTH;
			var rtPt:Object=new Object();
			rtPt.col=Math.floor(isoRTPt.x / _gridCellsize) + GRID_EXTEND_LENGTH;
			rtPt.row=Math.floor(isoRTPt.y / _gridCellsize) + GRID_EXTEND_LENGTH;
//			trace("左下角:",lbPt.col,lbPt.row);
//			trace("左上角:",ltPt.col,ltPt.row);
//			trace("右下角:",rbPt.col,rbPt.row);
//			trace("右上角:",rtPt.col,rtPt.row);
			var i:int;
			var j:int;
			for (i=0; i <= lbPt.col - ltPt.col; i++)
			{
				for (j=0; j <= rbPt.col - lbPt.col; j++)
				{
					if (lbPt.col + j - i <= 0 || lbPt.row - j - i <= 0)
						continue;
					if (isAdd)
						_buildingInfoGridArr[lbPt.col + j - i][lbPt.row - j - i].push((tile as BaseBuilding).uVO.buildingid);
					else
						_buildingInfoGridArr[lbPt.col + j - i][lbPt.row - j - i].splice(_buildingInfoGridArr[lbPt.col + j - i][lbPt.row - j - i].indexOf((tile as BaseBuilding).uVO.buildingid), 1);
				}
			}
			for (i=0; i <= lbPt.col - ltPt.col - 1; i++)
			{
				for (j=0; j <= rbPt.col - lbPt.col - 1; j++)
				{
					if (lbPt.col + j - i <= 0 || lbPt.row - 1 - j - i <= 0)
						continue;
					if (isAdd)
						_buildingInfoGridArr[lbPt.col + j - i][lbPt.row - 1 - j - i].push((tile as BaseBuilding).uVO.buildingid);
					else
						_buildingInfoGridArr[lbPt.col + j - i][lbPt.row - 1 - j - i].splice(_buildingInfoGridArr[lbPt.col + j - i][lbPt.row - 1 - j - i].indexOf((tile as BaseBuilding).uVO.buildingid), 1);
				}
			}
		}

//		private function onMouseMove(evt:ProxyEvent):void
//		{
//			checkMouseOver();
//		}

		private function onCityEnterFrame(evt:Event):void
		{
			if(_mouseOverEnable)
				checkMouseOver();
			updateCursorPosition();
		}
		
		/**
		 * 更新鼠标位置
		 */ 
		private function updateCursorPosition():void
		{
			_mouseCursorContainer.x=_city.mouseX+5;
			_mouseCursorContainer.y=_city.mouseY+5;
		}
		
		
		/**
		 * 禁用鼠标悬浮显示tip的效果
		 */
		public function closeMouseOverEffect():void
		{
			_mouseOverEnable=false;
			if(_mouseOverBuilding!=null)
				_mouseOverBuilding.doMouseOut();
		}
		
		/**
		 * 打开鼠标悬浮显示tip的效果
		 */
		public function openMouseOverEffect():void
		{
			_mouseOverEnable=true;
		}
		
		public function closeTileClick():void
		{
			_tileClickEnable=false;
		}
		
		public function openTileClick():void
		{
			_tileClickEnable=true;
		}
		
		public function disenableTileClickOnce():void
		{
			if(_mouseOverBuilding!=null)
				_isDisenableTileClickOnce=true;
		}
		

		/**
		 * 检查鼠标是否移动到物体上
		 * 若是则显示高亮效果
		 */
		private function checkMouseOver():void
		{
			if(_buildingInfoGridArr==null)
				return;
			var isoPt:Pt=IsoMath.screenToIso(new Pt((_cityView.currentX * _cityView.currentZoom + _city.mouseX - (_cityView.width / 2 - _cityView.width / 2 * _cityView.currentZoom) - _cityView.width / 2 * _cityView.currentZoom) / _cityView.currentZoom, (_city.mouseY + (_cityView.currentY - _cityView.height / 2) * _cityView.currentZoom - (_cityView.height / 2 - _cityView.height / 2 * _cityView.currentZoom)) / _cityView.currentZoom));
			var col:int=Math.floor(isoPt.x / _gridCellsize);
			var row:int=Math.floor(isoPt.y / _gridCellsize);
			var flag:Boolean;
			var tempBuilding:BaseBuilding;
			if (GRID_EXTEND_LENGTH + col < 0 || GRID_EXTEND_LENGTH + row < 0)
				return;
			if (col >= _gridCols || row >= _gridRows)
				return;
			for each (var buildingID:int in _buildingInfoGridArr[col + GRID_EXTEND_LENGTH][row + GRID_EXTEND_LENGTH])
			{
				var building:BaseBuilding=(this.getChildByID(buildingID.toString()) as BaseBuilding);
//				trace(building.vo.buildingname)
				var p:Pt=IsoMath.isoToScreen(new Pt(building.x, building.y));
				var offsetX:int=(_cityView.currentX * _cityView.currentZoom + _city.mouseX - (_cityView.width / 2 - _cityView.width / 2 * _cityView.currentZoom) - _cityView.width / 2 * _cityView.currentZoom) / _cityView.currentZoom - p.x;
				var offsetY:int=(_city.mouseY + (_cityView.currentY - _cityView.height / 2) * _cityView.currentZoom - (_cityView.height / 2 - _cityView.height / 2 * _cityView.currentZoom)) / _cityView.currentZoom - p.y;
//				trace(offsetX, offsetY);
//				trace(building.getRenderData().bitmapData.width,building.getRenderData().bitmapData.height);
				if (isActiveUnderPoint(building.getRenderData().bitmapData, offsetX, offsetY))
				{
//					trace(building.getRenderData().bitmapData.height,building.getRenderData().bitmapData.width);
					if (tempBuilding == null)
					{
						tempBuilding=building;
					}
					else
					{
						//深度低的优先显示
						if (tempBuilding.depth > building.depth)
							tempBuilding=building;
					}
					flag=true;
				}
				else
				{
					continue;

				}
			}
			if (_mouseOverBuilding != tempBuilding && flag)
			{
				if (_mouseOverBuilding != null)
				{
					_mouseOverBuilding.doMouseOut();
				}
				tempBuilding.doMouseOver();
//				trace("mouseOver");
				_mouseOverBuilding=tempBuilding;
			}
			if (_mouseOverBuilding != null && !flag)
			{
				_mouseOverBuilding.doMouseOut();
				_mouseOverBuilding=null;
			}

			//			_mouseOverBuilding=tempBuilding;
		}
		

		/**
		 * 检查图片的指定位置是否为透明像素
		 */
		private function isActiveUnderPoint(targetBitmapData:BitmapData, x:Number, y:Number):Boolean
		{
			if (targetBitmapData != null)
			{
				//首先得到全部的颜色信息
				var color:uint=targetBitmapData.getPixel32(x + targetBitmapData.width / 2, y + targetBitmapData.height);
				//然后右移24位以取到透明通道的值
				var alpha:uint=color >> 24;
				//比较透明通道的值是否非0并返回比较结果
				return alpha != 0;
			}
			return false;
		}


		private function onGroundSceneClik(evt:MouseEvent):void
		{
			if(!_tileClickEnable)
				return;
			if (_mouseOverBuilding == null)
				return;
			if (!this.contains(_mouseOverBuilding))
				return;
			if(_isDisenableTileClickOnce)
			{
				_isDisenableTileClickOnce=false;
				return;
			}
			_mouseOverBuilding.doMouseClick();

		}
	}
}
